package com.pack.joe.buglytinker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.pay.sdk.aidl.AidlUtils;
import com.pay.sdk.interfaces.GetPayStatusListener;
import com.pay.sdk.utils.WalletBrowerUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Joe on 2017/4/19 0019 09:31.
 * Wallet test  demo  MainActivity
 * Pull up the wallet to pay
 */

public class MainActivity extends Activity {
    /**
     * BaseApi Recommended by the server
     * Handle the submission parameters, tune up the wallet application
     **/
    private static final String BaseApi = "http://123ttd1.jtpay.com/pay/form/PullPay";// api pull up wallet BaseApi
    private static final String DownLaodAddress = "http://www.jtpay.com/apk/wallet.apk"; //wallet apk default download address
    //test Web page address
    private static final String TestUrl1 = "http://test.jtpay.com:8999/WebForm1.aspx";//waponestepurl
    private static final String TestUrl2 = "http://test.jtpay.com:8999/WebForm2.aspx";//wapurl
    private static final String TestUrl3 = "http://test.jtpay.com:8999/WebForm3.aspx";//sdkurl
    private static final String TestUrl4 = "http://test.jtpay.com:8999/WebForm4.aspx";//sdkonestepurl
    private TextView mTextView;
    private LinearLayout appParamLinearLayout;
    private EditText payPriceEditText;
    private EditText payGoodsEditText;
    private Spinner typeNameSpinner;
    private String payType = "3";//3 wx 4 ali
    private AidlUtils aidlUtils;//sdk paystatus no brower type   call back
    private WalletBrowerUtils mBrowerUtils;//integrated class method for pull up wallet
    private boolean isSDKPaying;
    private boolean isurlBrower;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWidget();
        initView();
    }

    private void initWidget() {
        mTextView = (TextView) findViewById(R.id.textView_test);
        appParamLinearLayout = (LinearLayout) findViewById(R.id.appParamLinearLayout);
        payPriceEditText = (EditText) findViewById(R.id.payPriceEditText);
        payGoodsEditText = (EditText) findViewById(R.id.payGoodsEditText);
        RadioGroup payTypeRadioGroup = (RadioGroup) findViewById(R.id.payTypeRadioGroup);
        typeNameSpinner = (Spinner) findViewById(R.id.type_name_spinner);
        Spinner achieveNameSpinner = (Spinner) findViewById(R.id.type_achieve_name_spinner);
        payTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (payType.equals("3")) {
                    payType = "4";
                } else {
                    payType = "3";
                }
            }
        });
        typeNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    appParamLinearLayout.setVisibility(View.GONE);
                } else {
                    appParamLinearLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        achieveNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                isurlBrower = position != 0;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initView() {
        //pay status listener
        GetPayStatusListener payStatusListener = new GetPayStatusListener() {
            @Override
            public void onPayStatus(String payStatus) {
                Log.d("junfutong", "callback result=" + payStatus);
                mTextView.append("|" + payStatus);
            }
        };
        aidlUtils = new AidlUtils(this, payStatusListener);
        mBrowerUtils = new WalletBrowerUtils(this);
        mBrowerUtils.setDownLaodAddress(DownLaodAddress);//set downloadAddress
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isSDKPaying) {
            isSDKPaying = false;
            aidlUtils.getPayStatus();//get pay status
        }
    }

    public void payWallet(View v) {
        switch (String.valueOf(v.getTag())) {
            case "checkoutWap":
            case "oneStepWap":
                if (typeNameSpinner.getSelectedItemPosition() == 0) {
                    //App organization parameters
                    payWap(v.getTag());
                } else {
                    payWapUrl(v.getTag());
                }
                break;
            case "checkoutSdk":
            case "oneStepSdk":
                if (typeNameSpinner.getSelectedItemPosition() == 0) {
                    //App organization parameters
                    paySdk(v.getTag());
                } else {
                    paySdkUrl(v.getTag());
                }
                break;
        }
    }

    /**
     * paySdkUrl
     **/
    public void paySdkUrl(Object type) {
        String url;
        //one step pay need ext_paytype
        if (type.equals("oneStepSdk")) {
            url = TestUrl4;
        } else {
            url = TestUrl3;
        }
        Log.d("junfutong", "pullup wap url=" + url);
        if (isurlBrower) {
            mBrowerUtils.choiceBrower(url);
        } else {
            /*The sdk call can add a payout callback notification*/
            isSDKPaying = true;
            aidlUtils.bindAidlService();// bind aidl callback service
            mBrowerUtils.pullUpWallet(url);
        }

    }

    /**
     * payWapUrl
     **/
    public void payWapUrl(Object type) {
        String url;
        //one step pay need ext_paytype
        if (type.equals("oneStepWap")) {
            url = TestUrl1;
        } else {
            url = TestUrl2;
        }
        Log.d("junfutong", "pullup wap url=" + url);
        if (isurlBrower) {
            mBrowerUtils.choiceBrower(url);
        } else {
            mBrowerUtils.pullUpWallet(url);
        }
    }

    /**
     * @ appid The unique identifier of the app。
     * pN_* See the 26 parameters of the access document
     **/
    public void paySdk(Object type) {
        //todo not recommended for comKey stored on the client
        String comKey = "40F4A509B7459D667B68C9A51A4E14DA";

        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String p1_usercode = "10208331";
        String p2_order = "TestOrder_" + dateFormat.format(date);
        String p3_money = payPriceEditText.getText().toString();
        String p4_returnurl = "http://pay.jtpay.com/Form/TestReturn";
        String p5_notifyurl = "http://pay.jtpay.com/Form/TestNotice";
        String p6_ordertime = dateFormat.format(date);
        /*
        *It is highly recommended that the p7_sign data signature process be completed on the server side,
        *very not recommended for merchant payment keys stored on the client
        *demo as a result of the show, in the mobile terminal
        * */
        String p7_sign = PayMD5Util.getMD5(p1_usercode + "&" + p2_order + "&" + p3_money +
                "&" + p4_returnurl + "&" + p5_notifyurl + "&" + p6_ordertime + comKey).toUpperCase();
        String p18_product = payGoodsEditText.getText().toString();
        String appid = "20161111102907658374";
        StringBuffer buffer = new StringBuffer();
        buffer.append(BaseApi);
        buffer.append("?p1_usercode=");
        buffer.append(p1_usercode);
        buffer.append("&p2_order=");
        buffer.append(p2_order);
        buffer.append("&p3_money=");
        buffer.append(p3_money);
        buffer.append("&p4_returnurl=");
        buffer.append(p4_returnurl);
        buffer.append("&p5_notifyurl=");
        buffer.append(p5_notifyurl);
        buffer.append("&p6_ordertime=");
        buffer.append(p6_ordertime);
        buffer.append("&p7_sign=");
        buffer.append(p7_sign);
        buffer.append("&p9_paymethod=");
        buffer.append("sdk");
        buffer.append("&p18_product=");
        buffer.append(p18_product);
        buffer.append("&ext_appid=");
        buffer.append(appid);
        //one step pay need ext_paytype
        if (type.equals("oneStepSdk")) {
            buffer.append("&ext_paytype=");
            buffer.append(payType);
        }
        String url = buffer.toString();
        Log.d("junfutong", "pullup sdk url=" + url);

        if (isurlBrower) {
            mBrowerUtils.choiceBrower(url);
        } else {
             /*The sdk call can add a payout callback notification*/
            isSDKPaying = true;
            aidlUtils.bindAidlService();// bind aidl callback service
            mBrowerUtils.pullUpWallet(url);
        }
    }

    /**
     * pN_* See the 26 parameters of the access document
     **/
    public void payWap(Object type) {
        /* very not recommended for comKey stored on the client */
        String comKey = "40F4A509B7459D667B68C9A51A4E14DA";

        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String p1_usercode = "10208331";//
        String p2_order = "TestOrder_" + dateFormat.format(date);
        String p3_money = payPriceEditText.getText().toString();
        String p4_returnurl = "http://pay.jtpay.com/Form/TestReturn";
        String p5_notifyurl = "http://pay.jtpay.com/Form/TestNotice";
        String p6_ordertime = dateFormat.format(date);
        /*
        *It is highly recommended that the p7_sign data signature process be completed on the server side,
        *very not recommended for merchant payment keys stored on the client
        *demo as a result of the show, in the mobile terminal
        * */
        String p7_sign = PayMD5Util.getMD5(p1_usercode + "&" + p2_order + "&" + p3_money +
                "&" + p4_returnurl + "&" + p5_notifyurl + "&" + p6_ordertime + comKey).toUpperCase();
        String p9_paymethod;

        if (type.equals("oneStepWap")) {
            //one step pay need p9_paymethod values specified payment method
            p9_paymethod = payType;
        } else {
            //wap pay need p9_paymethod values  unspecified payment method
            p9_paymethod = "wap";
        }
        String p14_customname = "name";
        String p17_customip = "ip";
        String p18_product = payGoodsEditText.getText().toString();
        String p25_terminal = "3";
        String p26_iswappay = "5";

        StringBuffer buffer = new StringBuffer();
        buffer.append(BaseApi);
        buffer.append("?p1_usercode=");
        buffer.append(p1_usercode);
        buffer.append("&p2_order=");
        buffer.append(p2_order);
        buffer.append("&p3_money=");
        buffer.append(p3_money);
        buffer.append("&p4_returnurl=");
        buffer.append(p4_returnurl);
        buffer.append("&p5_notifyurl=");
        buffer.append(p5_notifyurl);
        buffer.append("&p6_ordertime=");
        buffer.append(p6_ordertime);
        buffer.append("&p7_sign=");
        buffer.append(p7_sign);
        buffer.append("&p9_paymethod=");
        buffer.append(p9_paymethod);
        buffer.append("&p14_customname=");
        buffer.append(p14_customname);
        buffer.append("&p17_customip=");
        buffer.append(p17_customip);
        buffer.append("&p18_product=");
        buffer.append(p18_product);
        buffer.append("&p25_terminal=");
        buffer.append(p25_terminal);
        buffer.append("&p26_iswappay=");
        buffer.append(p26_iswappay);
        /*
        * Above for the need to wear the parameters, the following comment out the part of the
        * optional parameters can be added according to demand.
        * Optional parameter definitions Please refer to the documentation for 26 access parameter
        * descriptions
        */
        /*buffer.append("&p8_signtype=");
        buffer.append(p8_signtype);//user define
        buffer.append("&p10_paychannelnum=");
        buffer.append(p10_paychannelnum);//user define
        buffer.append("&p11_cardtype=");
        buffer.append(p11_cardtype);//user define
        buffer.append("&p12_channel=");
        buffer.append(p12_channel);//user define
        buffer.append("&p13_orderfailertime=");
        buffer.append(p13_orderfailertime);//user define
        buffer.append("&p15_customcontacttype=");
        buffer.append(p15_customcontacttype);//user define
        buffer.append("&p16_customcontact=");
        buffer.append(p16_customcontact);//user define
        buffer.append("&p19_productcat=");
        buffer.append(p19_productcat);//user define
        buffer.append("&p20_productnum=");
        buffer.append(p20_productnum);//user define
        buffer.append("&p21_pdesc=");
        buffer.append(p21_pdesc);//user define
        buffer.append("&p22_version=");
        buffer.append(p22_version);//user define
        buffer.append("&p23_charset=");
        buffer.append(p23_charset);//user define
        buffer.append("&p24_remark=");
        buffer.append(p24_remark);//user define*/
        String url = buffer.toString();
        Log.d("junfutong", "pullup wap url=" + url);
        if (isurlBrower) {
            mBrowerUtils.choiceBrower(url);
        } else {
            mBrowerUtils.pullUpWallet(url);
        }
    }

}
